<template>
  <a-card>
    <detail-list :col="2">
      <detail-list-item term="姓名">{{ planInfo.pyjh.xm }}</detail-list-item>
      <detail-list-item term="学号">{{ planInfo.pyjh.xh }}</detail-list-item>
      <detail-list-item term="培养单位">{{ planInfo.pyjh.dwmc }}</detail-list-item>
      <detail-list-item term="专业">{{ planInfo.pyjh.zymc }}</detail-list-item>
      <detail-list-item term="年级">{{ planInfo.pyjh.sznj }}</detail-list-item>
      <detail-list-item term="培养方案">{{ planInfo.pyjh.pyfamc }}</detail-list-item>
    </detail-list>

    <credit-table :pyfa="planInfo.pyfa" :pyjh="planInfo.pyjh" :countErr="countErr"/>
    <h4 style="margin-top:10px; margin-bottom:10px;">培养计划课程</h4>
    <a-form :form="form">
      <a-row :gutter="48">
        <a-col :md="8" :sm="12">
          <a-form-item label="培养单位"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}">
            <a-select v-decorator="['kcssyxm',
              {
                rules: [{ required: true, message: '请选择培养单位!' }],
              }]" @change="yxChange" showSearch :filterOption="filterOption">
              <a-select-option v-for="i in selectMenu.yxList" :key="i.id" :value="i.dwh">{{ i.dwh }} {{ i.dwmc }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item label="课程"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}">
            <a-select v-decorator="['kcIndex',
              {
                rules: [{ required: true, message: '请选择课程!' }],
              }]" showSearch :filterOption="filterOption">
              <a-spin v-if="kcLoading" slot="notFoundContent" size="small"/>
              <a-select-option v-for="(i,index) in selectMenu.courseList" :key="index" :value="index">{{ i.kch }}{{ i.kcmc }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-button type="primary" @click="addToList" style="margin:0 10px">添加到列表</a-button>
          <!-- <a-button type="primary" @click="deleteToList" style="margin:0 10px">删除</a-button> -->
        </a-col>
       </a-row>
    </a-form>
    <a-table
      rowKey="index"
      ref="table"
      :columns="columns"
      :dataSource="planInfo.pyjhkcList"
      :pagination="false"
      :rowSelection="rowSelection"
      :scroll="{ x: 1200 }">
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <span slot="kcshztmc" slot-scope="text, record">{{ record.sfmbkc == '1' ? '审核已通过' : text }}</span>
      <template slot="bxhxxmc" slot-scope="text, record, index">
        <a-radio-group v-if="record.sfmbkc !== '1'" :disabled="record.kcshzt === '02' || !selectedRowKeys.includes(index)" @change="e => xkChange(e.target.value, record)"  name="radioGroup" v-model="record.bxhxx">
          <a-radio value="0">选修</a-radio>
          <a-radio value="1">必修</a-radio>
        </a-radio-group>
        <span v-else>{{ text || (record.bxhxx == '0' ? '选修' : '必修') }}</span>
      </template>
      <template slot="sfxwkmc" slot-scope="text, record, index">
        <a-radio-group v-if="record.sfmbkc !== '1'" :disabled="record.bxhxx === '0' || record.kcshzt === '02' || !selectedRowKeys.includes(index)" @change="e => xwChange(e.target.value, record)"  name="radioGroup" v-model="record.sfxwk">
          <a-radio value="1">是</a-radio>
          <a-radio value="0">否</a-radio>
        </a-radio-group>
        <span v-else>{{ text || (record.sfxwk == '0' ? '否' : '是')}}</span>
      </template>
    </a-table>

    <h4 style="margin-top:10px; margin-bottom:10px;">培养过程</h4>
    <a-table
        rowKey="index"
        :columns="pcolumns"
        :dataSource="planInfo.pyjhPkcList"
        :pagination="false"
        :scroll="{x:1000}">>
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <span slot="kcshztmc" slot-scope="text, record">{{ (!record.pyfaId || record.sfmbkc != '1') ? text : '模板课程无需审核'}}</span>
    </a-table>
    <a-button slot="footer" type="primary" @click="() => { $emit('cancel') }">关闭</a-button>
    <div class="ant-pro-footer-toolbar">
      <a-button style="float: right;margin-top: 10px;" @click="submit" :loading="loadingBtn" type="primary">更新</a-button>
      <a-button style="float: right;margin-top: 10px;margin-right: 20px" @click="back" type="primary">返回</a-button>
    </div>
  </a-card>
</template>

<script>
import {message} from 'ant-design-vue'
import { mapState } from 'vuex'
import DetailList from '~/tool/DetailList'
import creditTable from './components/creditTable.vue'
const DetailListItem = DetailList.Item

export default {
  data () {
    return {
      countErr: -1,
      planInfo: {
        pyfa:{},
        pyjh: {},
        pyjhkcList: [],
        pyjhPkcList: []
      },
      columns: [
        {
          title: '序号',
          width: '50px',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '课程代码',
          width: '120px',
          dataIndex: 'kcdm'
        },
        {
          title: '课程名称',
          width: '150px',
          dataIndex: 'kcmc'
        },
        {
          title: '学时',
          width: '60px',
          dataIndex: 'xs'
        },
        {
          title: '学分',
          width: '60px',
          dataIndex: 'xf'
        },
        {
          title: '修课要求',
          width: '150px',
          dataIndex: 'bxhxxmc',
          scopedSlots: { customRender: 'bxhxxmc' }
        },
        {
          title: '是否学位课',
          width: '120px',
          dataIndex: 'sfxwkmc',
          scopedSlots: { customRender: 'sfxwkmc' }
        },
        {
          title: '导师审核',
          dataIndex: 'kcshztmc',
          width: '100px'
        },
        {
          title: '课程类型',
          width: '100px',
          dataIndex: 'kclxmc'
        }
      ],
      pcolumns: [
        {
          title: '课程代码',
          width: 100,
          dataIndex: 'kcdm',
          fixed:'left'
        },
        {
          title: '课程名称',
          width: 200,
          dataIndex: 'kcmc'
        },
        {
          title: '学时',
          dataIndex: 'xs'
        },
        {
          title: '学分',
          dataIndex: 'xf'
        },
        {
          title: '导师审核状态',
          dataIndex: 'kcshztmc',
          scopedSlots: { customRender: 'kcshztmc' }
        },
        {
          title: '课程类别',
          dataIndex: 'kclxmc'
        },
        {
          title: '审核意见',
          dataIndex: 'shyj'
        }
      ],
      form: this.$form.createForm(this),
      kcLoading: false,
      selectMenu: {},
      loadingBtn: false,
      selectedRowKeys: []
    }
  },
  components: {
    DetailList,
    DetailListItem,
    creditTable
  },
  computed: {
    ...mapState({
      TYPE0323: state => state.app['TYPE0323'],
      TYPE0065: state => state.app['TYPE0065']
    }),
    rowSelection () {
      const that = this
      return {
        selectedRowKeys: that.selectedRowKeys,
        hideDefaultSelections: false,
        onChange: selectedRowKeys => {
          const removeRowKeys = that.selectedRowKeys.filter(item=>selectedRowKeys.filter(_item=>_item === item).length==0);
          if(removeRowKeys.length>0){
          const _planInfo = that.planInfo;
          const _record = that.planInfo.pyjhkcList.filter((kc,index)=>index==removeRowKeys[0])[0];

          this.$api.cultivate.scoreStuList({kcdm:_record.kcdm,xh:_planInfo.pyjh.xh,xm:_planInfo.pyjh.xm}).then(res => {
              if(res && res.data && res.data.total>0){
                message.warning("已有成绩的课程不允许取消！");
                that.selectedRowKeys = that.selectedRowKeys
              }else{
                that.selectedRowKeys = selectedRowKeys
              }
            });
          }else{
            that.selectedRowKeys = selectedRowKeys
          }
        },
        onSelect: (record, selected) => {
          this.xfChange(record, selected)
        },
        onSelectAll: selected => {
          this.planInfo.pyjh.jhbxkms = 0
          this.planInfo.pyjh.jhbxkxf = 0
          this.planInfo.pyjh.jhxxkms = 0
          this.planInfo.pyjh.jhxxkxf = 0
          this.planInfo.pyjh.jhxwkms = 0
          this.planInfo.pyjh.jhxwkxf = 0
          if (selected) {
            this.selectedRowKeys = this.planInfo.pyjhkcList.map((kc,index) => {
              this.xfChange(kc, true)
              return index
            })
          } else {
            this.selectedRowKeys = this.planInfo.pyjhkcList.filter((kc,index) => {
              return kc.sfmbkc === '1'
            }).map((kc,index) => {
              this.xfChange(kc, true)
              return index
            })
          }
        },
        getCheckboxProps: record => ({
          props: {
            disabled: Boolean(record.kscj) // 有考试成绩的不能删除
            // disabled: record.sfmbkc === '1'
            // disabled: !!record.pyfaId || record.sfmbkc == '1' || record.kcshzt === '02'// 1为模板课程，不能删除
          }
        })
        // selectedRowKeys: that.selectedRowKeys,
        // onChange: selectedRowKeys => {
        //   that.selectedRowKeys = selectedRowKeys
        // },
        // getCheckboxProps: record => ({
        //   props: {
        //     disabled: record.sfmbkc === '1' // 1为模板课程，不能删除
        //   }
        // })
      }
    }
  },
  created () {
    message.loading('数据加载中...', 0)
    this.$store.dispatch('app/setDictionary', 'TYPE0323')
    this.$store.dispatch('app/setDictionary', 'TYPE0065')
    this.getInfo(this.$route.params.id)
    this.initSelectMenu()
  },
  methods: {
    initSelectMenu () {
      let allRequest = [
        this.$api.base.collegeAll()
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          yxList: res[0].data
        }
      })
    },
    filterOption (value, op) {
      return op.componentOptions.children[0].text.indexOf(value) !== -1
    },
    yxChange (code) {
      this.form.setFieldsValue({kcIndex: ''})
      this.$set(this.selectMenu, 'courseList', [])
      if (code) {
        this.kcLoading = true
        this.$api.cultivate.courseAll({kcssyxm: code}).then(res => {
          this.$set(this.selectMenu, 'courseList', res.data)
        }).finally(() => {
          this.kcLoading = false
        })
      } else {
        this.$set(this.selectMenu, 'courseList', [])
      }
    },
    getInfo (id) {
      this.$api.cultivate.planDetail(id).then(res => {
        message.destroy()
        this.planInfo = res.data
        let pyjhkcList = []
        let pyjhPkcList = [] //培养过程
        res.data.pyjhkcList.forEach(kc => {
          if (kc.kclxm == '7') {
            pyjhPkcList.push(kc)
          } else {
            pyjhkcList.push(kc)
          }
        })
        this.planInfo.pyjhPkcList = pyjhPkcList
        this.planInfo.pyjhkcList = pyjhkcList
        this.selectedRowKeys = pyjhkcList.map((e, i) => {
          return i
        })
      })
    },

    xfChange (kc, selected){
      if(selected){
        if(kc.bxhxx === '1'){ // 必修课
          this.planInfo.pyjh.jhbxkms += 1
          this.planInfo.pyjh.jhbxkxf += kc.xf
        }else{
          this.planInfo.pyjh.jhxxkms += 1
          this.planInfo.pyjh.jhxxkxf += kc.xf
        }
        if(kc.sfxwk === '1'){ // 学位课
          this.planInfo.pyjh.jhxwkms += 1
          this.planInfo.pyjh.jhxwkxf += kc.xf
        }
      }else{
        if(kc.bxhxx === '1'){ // 必修课
          this.planInfo.pyjh.jhbxkms -= 1
          this.planInfo.pyjh.jhbxkxf -= kc.xf
        }else{
          this.planInfo.pyjh.jhxxkms -= 1
          this.planInfo.pyjh.jhxxkxf -= kc.xf
        }
        if(kc.sfxwk === '1'){ // 学位课
          this.planInfo.pyjh.jhxwkms -= 1
          this.planInfo.pyjh.jhxwkxf -= kc.xf
        }
      }
    },
    xkChange (e, kc) {
      if (e === '0') {
        if(this.planInfo.pyjh.jhbxkms > 0){
          this.planInfo.pyjh.jhbxkms--
          this.planInfo.pyjh.jhbxkxf = this.planInfo.pyjh.jhbxkxf - kc.xf
        }
        this.planInfo.pyjh.jhxxkms++
        this.planInfo.pyjh.jhxxkxf = this.planInfo.pyjh.jhxxkxf + kc.xf
        if(kc.sfxwk === '1'){
          kc.sfxwk = '0'
          this.xwChange('0', kc)
        }
      } else {
        if(this.planInfo.pyjh.jhxxkms > 0){
          this.planInfo.pyjh.jhxxkms--
          this.planInfo.pyjh.jhxxkxf = this.planInfo.pyjh.jhxxkxf - kc.xf
        }
        this.planInfo.pyjh.jhbxkms++
        this.planInfo.pyjh.jhbxkxf = this.planInfo.pyjh.jhbxkxf + kc.xf
      }
    },
    xwChange (e, kc) {
      if (e === '1') {
        this.planInfo.pyjh.jhxwkms++
        this.planInfo.pyjh.jhxwkxf += kc.xf
      } else {
        if(this.planInfo.pyjh.jhxwkms > 0){
          this.planInfo.pyjh.jhxwkms--
          this.planInfo.pyjh.jhxwkxf -= kc.xf
        }
      }
    },
    addToList () {
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        let kc = {...this.selectMenu.courseList[values.kcIndex]}
        let index = this.planInfo.pyjhkcList.findIndex(course => {
          return course.kcdm == kc.kch
        })
        if (index !== -1) {
          this.$message.warn('不能重复添加课程')
          return
        }
        kc.kcdm = kc.kch
        kc.xs = kc.zxs
        kc.kclxmc = kc.kclbmc
        kc.bxhxx = '0'
        kc.sfxwk = '0'
        kc.sfmbkc = '0'
        this.selectedRowKeys.push(this.planInfo.pyjhkcList.length)
        this.planInfo.pyjhkcList.push(kc)
        this.xfChange(kc, true);
      })
    },
    // deleteToList () {
    //   this.selectedRowKeys.forEach(index => {
    //     let kc = this.planInfo.pyjhkcList[index]
    //     if (kc.sfxwk === '1') {
    //       this.planInfo.pyjh.jhxwkms--
    //       this.planInfo.pyjh.jhxwkxf -= kc.xf
    //     }
    //     if (kc.bxhxx === '0') {
    //       this.planInfo.pyjh.jhxxkms--
    //       this.planInfo.pyjh.jhxxkxf -= kc.xf
    //     } else {
    //       this.planInfo.pyjh.jhbxkms--
    //       this.planInfo.pyjh.jhbxkxf -= kc.xf
    //     }
    //   })
    //   this.planInfo.pyjhkcList = this.planInfo.pyjhkcList.filter((kc, index) => {
    //     return !this.selectedRowKeys.includes(index)
    //   })
    //   // this.$refs.table.clearSelected()
    //   this.selectedRowKeys = []
    //   // console.log(this.selectedRowKeys)
    // },
    submit () {
      if (this.planInfo.pyjhkcList.length) {

        const jhzxf = this.planInfo.pyjh.jhxxkxf + this.planInfo.pyjh.jhbxkxf

        if(this.planInfo.pyfa.kczxf > jhzxf){
          this.countErr = 0;
          this.$message.warn("培养计划课程总学分必须高于培养方案设置的最低学分")
          return
        }
        if(this.planInfo.pyfa.kczgxf < jhzxf){
          this.countErr = 1;
          this.$message.warn("培养计划课程总学分必须低于培养方案设置的最高学分")
          return
        }
        if(this.planInfo.pyfa.bxkxf > this.planInfo.pyjh.jhbxkxf){
          this.countErr = 2;
          this.$message.warn("必修课学分不能低于培养方案要求")
          return
        }
        if(this.planInfo.pyfa.bxkms > this.planInfo.pyjh.jhbxkms){
          this.countErr = 3;
          this.$message.warn("必修课门数不能低于培养方案要求")
          return
        }
        if(this.planInfo.pyfa.xxkxf > this.planInfo.pyjh.jhxxkxf){
          this.countErr = 4;
          this.$message.warn("选修课学分不能低于培养方案要求")
          return
        }
        if(this.planInfo.pyfa.xxkms > this.planInfo.pyjh.jhxxkms){
          this.countErr = 5;
          this.$message.warn("选修课门数不能低于培养方案要求")
          return
        }
        if(this.planInfo.pyfa.xwkxf > this.planInfo.pyjh.jhxwkxf){
          this.countErr = 6;
          this.$message.warn("学位课课学分不能低于培养方案要求")
          return
        }
        if(this.planInfo.pyfa.xwkms > this.planInfo.pyjh.jhxwkms){
          this.countErr = 7;
          this.$message.warn("学位课门数不能低于培养方案要求")
          return
        }
        this.countErr = -1
      } else {
        return this.$message.warn('课程列表不能为空')
      }
      this.loadingBtn = true
      let pyjhkcList = this.planInfo.pyjhkcList.filter((kc,index) => {
        return this.selectedRowKeys.includes(index)
      })
      pyjhkcList.push(...this.planInfo.pyjhPkcList)
      let pyjhkcPropDTOList = pyjhkcList.map(item => {
        return {
          pyjhkcId: item.id,
          bxhxx: item.bxhxx,
          kcdm: item.kcdm,
          sfxwk: item.sfxwk,
          sfmbkc: item.sfmbkc ? item.sfmbkc : '0'
        }
      })
      this.$api.cultivate.planUpdate({pyjhId: this.planInfo.pyjh.id, pyjhkcPropDTOList, xh: this.planInfo.pyjh.xh}).then(res => {
        this.$message.success(res.msg)
        this.$router.back()
      }).finally(() => {
        this.loadingBtn = false
      })
    },
    back() {
      this.$router.back()
    }
  }
}
</script>

<style>
</style>
